package dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import br.com.sigcoap.interfaces.IGenericDAO;
import br.com.sigcoap.interfaces.IBaseEntity;

public abstract class AbstractGenericDao<T extends IBaseEntity<?>> implements IGenericDAO<T> {
	
	private EntityManager entityManager;
	
	public AbstractGenericDao() {
		entityManager =Persistence.createEntityManagerFactory("jpasigcoap").createEntityManager();
	}

	@Override
	public void beginTransaction() {
		if(getEntityManager().isOpen()){
			getEntityManager().getTransaction().begin();
		}
		
	}

	@Override
	public void commitTransaction() {
		if(getEntityManager().isOpen()){
			getEntityManager().getTransaction().commit();;
		}
	}

	@Override
	public void save(T entity) {
		if(entity.getId() == null){
			getEntityManager().persist(entity);	
			getEntityManager().flush();
		}else{
			getEntityManager().merge(entity);
		}
		
	}

	@Override
	public void delete(T entity) {
		getEntityManager().remove(entity);
	}

	@Override
	public T find(T entity) {
		return	(T) getEntityManager().find(entity.getClass(), entity);
	}
	
	public void rollback(){
		getEntityManager().getTransaction().rollback();
	}
	
	protected EntityManager getEntityManager(){
		return entityManager; 
	}

}
